import React, { useState, useEffect, useCallback } from 'react';
import { FiDownload, FiTrash2, FiClock, FiHardDrive, FiDatabase, FiCheckCircle, FiAlertCircle, FiRefreshCw } from 'react-icons/fi';
import { novelOperations } from '../db/operations';
import db from '../db/database';
import { useTheme } from '../contexts/ThemeContext';

/**
 * 离线管理组件 - 管理缓存和预下载
 */
const OfflineManager = () => {
  const { isDarkMode } = useTheme();
  
  // 状态
  const [cachedNovels, setCachedNovels] = useState([]);
  const [cacheQueue, setCacheQueue] = useState([]);
  const [backups, setBackups] = useState([]);
  const [cacheStats, setCacheStats] = useState(null);
  const [loading, setLoading] = useState(true);
  const [activeTab, setActiveTab] = useState('cached');
  const [processingIds, setProcessingIds] = useState([]);
  const [selectedNovels, setSelectedNovels] = useState([]);
  const [error, setError] = useState(null);
  const [successMessage, setSuccessMessage] = useState(null);
  
  // 加载数据
  const loadData = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);
      
      // 获取已缓存的小说
      const novels = await db.novels.where('cached').equals(true).toArray();
      setCachedNovels(novels);
      
      // 获取缓存队列
      const queue = await novelOperations.getCacheQueue();
      setCacheQueue(queue);
      
      // 获取备份列表
      const backupsList = await novelOperations.getBackups();
      setBackups(backupsList);
      
      // 获取缓存统计
      const stats = await novelOperations.getCacheStats();
      setCacheStats(stats);
      
      setLoading(false);
    } catch (err) {
      console.error('加载离线数据失败:', err);
      setError('加载数据失败：' + err.message);
      setLoading(false);
    }
  }, []);
  
  // 初始加载
  useEffect(() => {
    loadData();
  }, [loadData]);
  
  // 处理缓存队列
  const handleProcessQueue = async () => {
    try {
      setProcessingIds(['queue']);
      
      // 处理队列
      const results = await novelOperations.processCacheQueue();
      
      // 显示成功消息
      if (results.length > 0) {
        setSuccessMessage(`已处理 ${results.length} 个缓存任务`);
        setTimeout(() => setSuccessMessage(null), 3000);
      } else {
        setSuccessMessage('没有需要处理的缓存任务');
        setTimeout(() => setSuccessMessage(null), 3000);
      }
      
      // 重新加载数据
      await loadData();
    } catch (err) {
      console.error('处理缓存队列失败:', err);
      setError('处理队列失败：' + err.message);
    } finally {
      setProcessingIds([]);
    }
  };
  
  // 添加小说到缓存队列
  const handleAddToQueue = async (novel, priority = 'medium') => {
    try {
      setProcessingIds(prev => [...prev, novel.id]);
      
      // 添加到队列
      const result = await novelOperations.preCacheNovel(novel.id, priority);
      
      if (result.status === 'queued') {
        setSuccessMessage(`已将《${novel.name}》添加到缓存队列`);
      } else if (result.status === 'already_cached') {
        setSuccessMessage(`《${novel.name}》已经缓存，无需重复添加`);
      }
      
      setTimeout(() => setSuccessMessage(null), 3000);
      
      // 重新加载队列数据
      await loadData();
    } catch (err) {
      console.error('添加到缓存队列失败:', err);
      setError('添加失败：' + err.message);
    } finally {
      setProcessingIds(prev => prev.filter(id => id !== novel.id));
    }
  };
  
  // 删除缓存
  const handleDeleteCache = async (novel) => {
    if (!window.confirm(`确定要删除《${novel.name}》的缓存吗？这将移除所有离线内容。`)) {
      return;
    }
    
    try {
      setProcessingIds(prev => [...prev, novel.id]);
      
      // 更新小说缓存状态
      await db.novels.update(novel.id, { cached: false });
      
      // 删除内容分片
      await db.contents.where('novelId').equals(novel.id).delete();
      
      // 删除缓存信息
      await db.cacheInfo.delete(novel.id);
      
      setSuccessMessage(`已删除《${novel.name}》的缓存`);
      setTimeout(() => setSuccessMessage(null), 3000);
      
      // 重新加载数据
      await loadData();
    } catch (err) {
      console.error('删除缓存失败:', err);
      setError('删除失败：' + err.message);
    } finally {
      setProcessingIds(prev => prev.filter(id => id !== novel.id));
    }
  };
  
  // 创建备份
  const handleCreateBackup = async () => {
    try {
      setProcessingIds(prev => [...prev, 'backup']);
      
      // 创建备份
      const result = await novelOperations.backupCachedNovels({
        includeContent: false, // 默认不包含内容，避免备份过大
        includeChapters: true,
        includeProgress: true
      });
      
      if (result.status === 'success') {
        setSuccessMessage(`已成功创建 ${result.backup.count} 本小说的备份`);
      } else if (result.status === 'no_data') {
        setSuccessMessage('没有已缓存的小说可供备份');
      }
      
      setTimeout(() => setSuccessMessage(null), 3000);
      
      // 重新加载数据
      await loadData();
    } catch (err) {
      console.error('创建备份失败:', err);
      setError('备份失败：' + err.message);
    } finally {
      setProcessingIds(prev => prev.filter(id => id !== 'backup'));
    }
  };
  
  // 恢复备份
  const handleRestoreBackup = async (backup) => {
    if (!window.confirm(`确定要从 ${new Date(backup.timestamp).toLocaleString()} 的备份中恢复数据吗？这可能会覆盖当前的阅读进度。`)) {
      return;
    }
    
    try {
      setProcessingIds(prev => [...prev, backup.id]);
      
      // 恢复备份
      const result = await novelOperations.restoreFromBackup(backup.id);
      
      if (result.status === 'success') {
        setSuccessMessage(`已成功恢复 ${result.count} 本小说的数据`);
      }
      
      setTimeout(() => setSuccessMessage(null), 3000);
      
      // 重新加载数据
      await loadData();
    } catch (err) {
      console.error('恢复备份失败:', err);
      setError('恢复失败：' + err.message);
    } finally {
      setProcessingIds(prev => prev.filter(id => id !== backup.id));
    }
  };
  
  // 清理数据库
  const handleDbMaintenance = async () => {
    try {
      setProcessingIds(prev => [...prev, 'maintenance']);
      
      // 执行数据库维护
      const result = await db.maintenance();
      
      if (result.status === 'success') {
        setSuccessMessage(`数据库清理完成，删除了 ${result.deletedTasks} 个过期任务和 ${result.cleanedBackups} 个旧备份`);
      } else if (result.status === 'skipped') {
        setSuccessMessage('数据库维护已跳过：' + result.reason);
      }
      
      setTimeout(() => setSuccessMessage(null), 3000);
      
      // 重新加载数据
      await loadData();
    } catch (err) {
      console.error('数据库维护失败:', err);
      setError('维护失败：' + err.message);
    } finally {
      setProcessingIds(prev => prev.filter(id => id !== 'maintenance'));
    }
  };
  
  // 格式化日期
  const formatDate = (timestamp) => {
    if (!timestamp) return '';
    
    const date = new Date(timestamp);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
  };
  
  // 格式化文件大小
  const formatSize = (bytes) => {
    if (bytes < 1024) return bytes + ' B';
    if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(2) + ' KB';
    return (bytes / (1024 * 1024)).toFixed(2) + ' MB';
  };
  
  return (
    <div className={`max-w-4xl mx-auto p-4 ${isDarkMode ? 'text-gray-200' : 'text-gray-800'}`}>
      <h1 className="text-2xl font-bold mb-6">离线阅读管理</h1>
      
      {/* 消息提示 */}
      {error && (
        <div className="bg-red-500 text-white p-3 rounded-md mb-4 flex items-center">
          <FiAlertCircle className="mr-2" />
          {error}
          <button onClick={() => setError(null)} className="ml-auto">×</button>
        </div>
      )}
      
      {successMessage && (
        <div className="bg-green-500 text-white p-3 rounded-md mb-4 flex items-center">
          <FiCheckCircle className="mr-2" />
          {successMessage}
          <button onClick={() => setSuccessMessage(null)} className="ml-auto">×</button>
        </div>
      )}
      
      {/* 缓存统计 */}
      {cacheStats && (
        <div className={`${isDarkMode ? 'bg-gray-800' : 'bg-white'} rounded-lg shadow p-4 mb-6`}>
          <h2 className="text-lg font-semibold mb-3 flex items-center">
            <FiHardDrive className="mr-2" /> 缓存统计
          </h2>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div className={`${isDarkMode ? 'bg-gray-700' : 'bg-gray-100'} p-3 rounded-md`}>
              <p className="text-sm opacity-70">缓存小说</p>
              <p className="text-xl font-semibold">{cacheStats.cachedNovels} 本</p>
            </div>
            <div className={`${isDarkMode ? 'bg-gray-700' : 'bg-gray-100'} p-3 rounded-md`}>
              <p className="text-sm opacity-70">缓存大小</p>
              <p className="text-xl font-semibold">{cacheStats.sizeMB} MB</p>
            </div>
            <div className={`${isDarkMode ? 'bg-gray-700' : 'bg-gray-100'} p-3 rounded-md`}>
              <p className="text-sm opacity-70">分片数量</p>
              <p className="text-xl font-semibold">{cacheStats.chunksCount} 个</p>
            </div>
          </div>
        </div>
      )}
      
      {/* 操作按钮 */}
      <div className="flex flex-wrap gap-3 mb-6">
        <button 
          onClick={handleProcessQueue} 
          disabled={processingIds.includes('queue')}
          className={`flex items-center px-4 py-2 rounded-md ${isDarkMode ? 'bg-blue-600 hover:bg-blue-700' : 'bg-blue-500 hover:bg-blue-600'} text-white disabled:opacity-50`}
        >
          {processingIds.includes('queue') ? (
            <>
              <FiRefreshCw className="mr-2 animate-spin" /> 处理中...
            </>
          ) : (
            <>
              <FiDownload className="mr-2" /> 处理缓存队列
            </>
          )}
        </button>
        
        <button 
          onClick={handleCreateBackup} 
          disabled={processingIds.includes('backup')}
          className={`flex items-center px-4 py-2 rounded-md ${isDarkMode ? 'bg-green-600 hover:bg-green-700' : 'bg-green-500 hover:bg-green-600'} text-white disabled:opacity-50`}
        >
          {processingIds.includes('backup') ? (
            <>
              <FiRefreshCw className="mr-2 animate-spin" /> 备份中...
            </>
          ) : (
            <>
              <FiDatabase className="mr-2" /> 创建备份
            </>
          )}
        </button>
        
        <button 
          onClick={handleDbMaintenance} 
          disabled={processingIds.includes('maintenance')}
          className={`flex items-center px-4 py-2 rounded-md ${isDarkMode ? 'bg-purple-600 hover:bg-purple-700' : 'bg-purple-500 hover:bg-purple-600'} text-white disabled:opacity-50`}
        >
          {processingIds.includes('maintenance') ? (
            <>
              <FiRefreshCw className="mr-2 animate-spin" /> 清理中...
            </>
          ) : (
            <>
              <FiClock className="mr-2" /> 清理过期数据
            </>
          )}
        </button>
      </div>
      
      {/* 标签切换 */}
      <div className="flex border-b mb-4">
        <button 
          className={`py-2 px-4 ${activeTab === 'cached' ? 
            (isDarkMode ? 'border-b-2 border-blue-400 text-blue-400' : 'border-b-2 border-blue-500 text-blue-600') : 
            'text-gray-500'}`}
          onClick={() => setActiveTab('cached')}
        >
          已缓存小说 ({cachedNovels.length})
        </button>
        <button 
          className={`py-2 px-4 ${activeTab === 'queue' ? 
            (isDarkMode ? 'border-b-2 border-blue-400 text-blue-400' : 'border-b-2 border-blue-500 text-blue-600') : 
            'text-gray-500'}`}
          onClick={() => setActiveTab('queue')}
        >
          缓存队列 ({cacheQueue.length})
        </button>
        <button 
          className={`py-2 px-4 ${activeTab === 'backups' ? 
            (isDarkMode ? 'border-b-2 border-blue-400 text-blue-400' : 'border-b-2 border-blue-500 text-blue-600') : 
            'text-gray-500'}`}
          onClick={() => setActiveTab('backups')}
        >
          备份管理 ({backups.length})
        </button>
      </div>
      
      {/* 加载指示器 */}
      {loading && (
        <div className="flex justify-center items-center py-12">
          <div className="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-blue-500"></div>
          <p className="ml-3 text-gray-500">加载中...</p>
        </div>
      )}
      
      {/* 已缓存小说列表 */}
      {activeTab === 'cached' && !loading && (
        <div className={`${isDarkMode ? 'bg-gray-800' : 'bg-white'} rounded-lg shadow`}>
          {cachedNovels.length === 0 ? (
            <div className="p-6 text-center text-gray-500">
              <FiDatabase className="mx-auto mb-2 text-3xl" />
              <p>暂无已缓存的小说</p>
            </div>
          ) : (
            <table className="w-full">
              <thead className={`${isDarkMode ? 'bg-gray-700 text-gray-200' : 'bg-gray-100 text-gray-700'}`}>
                <tr>
                  <th className="py-2 px-4 text-left">书名</th>
                  <th className="py-2 px-4 text-left">大小</th>
                  <th className="py-2 px-4 text-left">缓存时间</th>
                  <th className="py-2 px-4 text-left">操作</th>
                </tr>
              </thead>
              <tbody>
                {cachedNovels.map(novel => (
                  <tr key={novel.id} className={`${isDarkMode ? 'border-gray-700' : 'border-gray-200'} border-t`}>
                    <td className="py-3 px-4">{novel.name}</td>
                    <td className="py-3 px-4">{formatSize(novel.size || 0)}</td>
                    <td className="py-3 px-4">{formatDate(novel.modified)}</td>
                    <td className="py-3 px-4">
                      <button 
                        onClick={() => handleDeleteCache(novel)}
                        disabled={processingIds.includes(novel.id)}
                        className={`flex items-center px-2 py-1 rounded ${isDarkMode ? 'bg-red-800 hover:bg-red-700' : 'bg-red-100 hover:bg-red-200'} ${isDarkMode ? 'text-red-200' : 'text-red-600'} text-sm`}
                      >
                        {processingIds.includes(novel.id) ? (
                          <FiRefreshCw className="mr-1 animate-spin" />
                        ) : (
                          <FiTrash2 className="mr-1" />
                        )}
                        删除缓存
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>
      )}
      
      {/* 缓存队列 */}
      {activeTab === 'queue' && !loading && (
        <div className={`${isDarkMode ? 'bg-gray-800' : 'bg-white'} rounded-lg shadow`}>
          {cacheQueue.length === 0 ? (
            <div className="p-6 text-center text-gray-500">
              <FiClock className="mx-auto mb-2 text-3xl" />
              <p>缓存队列为空</p>
            </div>
          ) : (
            <table className="w-full">
              <thead className={`${isDarkMode ? 'bg-gray-700 text-gray-200' : 'bg-gray-100 text-gray-700'}`}>
                <tr>
                  <th className="py-2 px-4 text-left">小说ID</th>
                  <th className="py-2 px-4 text-left">优先级</th>
                  <th className="py-2 px-4 text-left">状态</th>
                  <th className="py-2 px-4 text-left">进度</th>
                  <th className="py-2 px-4 text-left">请求时间</th>
                </tr>
              </thead>
              <tbody>
                {cacheQueue.map(task => (
                  <tr key={task.id} className={`${isDarkMode ? 'border-gray-700' : 'border-gray-200'} border-t`}>
                    <td className="py-3 px-4">{task.id}</td>
                    <td className="py-3 px-4">
                      <span className={`px-2 py-0.5 rounded-full text-xs ${
                        task.priority === 'high' 
                          ? 'bg-red-100 text-red-800' 
                          : task.priority === 'medium'
                            ? 'bg-yellow-100 text-yellow-800'
                            : 'bg-blue-100 text-blue-800'
                      }`}>
                        {task.priority === 'high' ? '高' : task.priority === 'medium' ? '中' : '低'}
                      </span>
                    </td>
                    <td className="py-3 px-4">
                      <span className={`px-2 py-0.5 rounded-full text-xs ${
                        task.status === 'completed' 
                          ? 'bg-green-100 text-green-800' 
                          : task.status === 'failed'
                            ? 'bg-red-100 text-red-800'
                            : task.status === 'processing' || task.status === 'downloading'
                              ? 'bg-blue-100 text-blue-800'
                              : 'bg-gray-100 text-gray-800'
                      }`}>
                        {task.status === 'pending' ? '等待中' : 
                         task.status === 'processing' ? '处理中' :
                         task.status === 'downloading' ? '下载中' :
                         task.status === 'completed' ? '已完成' :
                         task.status === 'failed' ? '失败' : task.status}
                      </span>
                    </td>
                    <td className="py-3 px-4">
                      {task.progress ? `${Math.round(task.progress)}%` : '-'}
                    </td>
                    <td className="py-3 px-4">{formatDate(task.requestTime)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>
      )}
      
      {/* 备份管理 */}
      {activeTab === 'backups' && !loading && (
        <div className={`${isDarkMode ? 'bg-gray-800' : 'bg-white'} rounded-lg shadow`}>
          {backups.length === 0 ? (
            <div className="p-6 text-center text-gray-500">
              <FiDatabase className="mx-auto mb-2 text-3xl" />
              <p>暂无备份记录</p>
            </div>
          ) : (
            <table className="w-full">
              <thead className={`${isDarkMode ? 'bg-gray-700 text-gray-200' : 'bg-gray-100 text-gray-700'}`}>
                <tr>
                  <th className="py-2 px-4 text-left">备份ID</th>
                  <th className="py-2 px-4 text-left">时间</th>
                  <th className="py-2 px-4 text-left">小说数量</th>
                  <th className="py-2 px-4 text-left">大小</th>
                  <th className="py-2 px-4 text-left">操作</th>
                </tr>
              </thead>
              <tbody>
                {backups.map(backup => (
                  <tr key={backup.id} className={`${isDarkMode ? 'border-gray-700' : 'border-gray-200'} border-t`}>
                    <td className="py-3 px-4">{backup.id}</td>
                    <td className="py-3 px-4">{formatDate(backup.timestamp)}</td>
                    <td className="py-3 px-4">{backup.count} 本</td>
                    <td className="py-3 px-4">{formatSize(backup.size || 0)}</td>
                    <td className="py-3 px-4">
                      <button 
                        onClick={() => handleRestoreBackup(backup)}
                        disabled={processingIds.includes(backup.id)}
                        className={`flex items-center px-2 py-1 rounded ${isDarkMode ? 'bg-green-800 hover:bg-green-700' : 'bg-green-100 hover:bg-green-200'} ${isDarkMode ? 'text-green-200' : 'text-green-600'} text-sm`}
                      >
                        {processingIds.includes(backup.id) ? (
                          <FiRefreshCw className="mr-1 animate-spin" />
                        ) : (
                          <FiDatabase className="mr-1" />
                        )}
                        恢复
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>
      )}
    </div>
  );
};

export default OfflineManager; 